from flask import Blueprint, request
from utilsapp.mysql_con import db_pagelist, db_fetchone, db_delete, db_update
from utilsapp.common import assign_value, parsing_data_id

bluePrint = Blueprint("notice", __name__)
tableName = "notice"


# 分页查询
@bluePrint.route("/getlist", methods=["post"])
def table_list():
    sql = f"""SELECT n.*, u1.nick_name as pull_name,u2.nick_name as accept_name,d.device_name
    from notice n
    JOIN userinfo u1 on u1.id = n.user_id
    JOIN userinfo u2 on u2.id = n.accept_id
    JOIN device d on n.device_id = d.id """
    query = " where 1 = 1 "
    a = request.json
    scope_id = assign_value(a, "scope_id", 0)
    scoped = parsing_data_id(scope_id, request)
    device_name = assign_value(a, "device_name")
    start_time = assign_value(a, "start_time")
    end_time = assign_value(a, "end_time")
    status = assign_value(a, "status")
    desc = assign_value(a, "desc")
    if scoped != "":
        query += f" and d.{scoped} "
    if device_name != "":
        query += f" and d.device_name like '%{device_name}%' "
    if start_time != "":
        query += f" and n.end_time >'{start_time}'"
    if end_time != "":
        query += f" and n.end_time <'{end_time}' "
    if status != "":
        query += f" and n.status = {status}"
    sql += query + " ORDER BY end_time desc"
    sql_ = f"select count(status) as num from ({sql}) as a where status = "
    num1 = db_fetchone(sql_ + "1")
    num2 = db_fetchone(sql_ + "2")
    num3 = db_fetchone(sql_ + "3")
    res = db_pagelist(sql, a["page"])

    res["stat"] = {
        "handled": num1["data"],
        "unHandled": num2["data"],
        "confirmed": num3["data"],
    }

    return res


@bluePrint.route("/delete", methods=["post"])
def a():
    id_ = assign_value(request.json, "id")
    return db_delete("notice", f"WHERE id = %s", {"id_": id_})


@bluePrint.route("/edit", methods=["post"])
def b():
    title = assign_value(request.json, "title")
    content = assign_value(request.json, "content")
    id_ = assign_value(request.json, "id")
    status = assign_value(request.json, "status")
    notice = 4
    if status != 3:
        status = 1
        notice = 2
    device_id = assign_value(request.json, "device_id")
    db_update(
        "warn", {"notice": notice}, f"where device_id = %s", {"device_id": device_id}
    )
    db_update(
        "mqtt",
        {
            "handle": 1,
            "content": f"设备{assign_value(request.json, 'title')}工单已处理,处理内容为{assign_value(request.json, 'content')}",
        },
        f"where device_id = %s",
        {"device_id": device_id},
    )
    return db_update(
        "notice",
        {"title": title, "content": content, "status": status},
        f"where id =%s",
        {"id_": id_},
    )
